/*
 * @lc app=leetcode.cn id=1001 lang=typescript
 *
 * [1001] 网格照明
 */

// @lc code=start
function gridIllumination(n: number, lamps: number[][], queries: number[][]): number[] {
  // 行、列，对角线的点亮数量
  const rowMap = new Map<number, number>();
  const colMap = new Map<number, number>();
  const diagnoal = new Map<number, number>();
  const antiDiagnoal = new Map<number, number>();
  // 点亮的灯的位置
  const lampsPos = new Set<string>();

  // 初始化
  const m = lamps.length;
  for (let i = 0; i < m; i++) {
    const [x, y] = lamps[i];
    const key = `${x}-${y}`;
    // 相同位置的灯去重
    if (lampsPos.has(key)) continue;
    // 灯的位置
    lampsPos.add(key);
    // 灯光覆盖的位置
    rowMap.set(x, (rowMap.get(x) || 0) + 1);
    colMap.set(y, (colMap.get(y) || 0) + 1);
    diagnoal.set(x - y, (diagnoal.get(x - y) || 0) + 1);
    antiDiagnoal.set(x + y, (antiDiagnoal.get(x + y) || 0) + 1);
  }

  const ans = new Array(queries.length).fill(0);
  // 遍历queries，查询结果
  for (let i = 0; i < queries.length; i++) {
    const [row, col] = queries[i];
    // 判断行、列、对角线、反对角线是否有灯光
    if (
      rowMap.get(row) ||
      colMap.get(col) ||
      diagnoal.get(row - col) ||
      antiDiagnoal.get(row + col)
    ) {
      // 在灯光内，该位置为1
      ans[i] = 1;
    }
    // 遍历周围8个方向是否有灯，有的话关闭
    for (let x = row - 1; x <= row + 1; x++) {
      for (let y = col - 1; y <= col + 1; y++) {
        const key = `${x}-${y}`;
        // 坐标超出范围
        if (x < 0 || x >= n || y < 0 || y >= n) continue;
        // 当前坐标不是灯的位置
        if (!lampsPos.has(key)) continue;
        // 关闭灯
        lampsPos.delete(key);
        // 关闭灯光，相应位置的灯光数量减1
        rowMap.set(x, rowMap.get(x) - 1);
        colMap.set(y, colMap.get(y) - 1);
        diagnoal.set(x - y, diagnoal.get(x - y) - 1);
        antiDiagnoal.set(x + y, antiDiagnoal.get(x + y) - 1);
      }
    }
  }
  return ans;
}
// @lc code=end
